package main

import (
	"encoding/json"
	"gorm.io/gorm"
)

func getAllVote(organID string, db *gorm.DB) []*Vote {
	var res []SavedVote
	var results []*Vote
	db.Where("Org_Id = ?", organID).Find(&res)
	for _, r := range res {
		var voters map[string]Voter
		err := json.Unmarshal(r.Voters, &voters)
		if err != nil {
			return nil
		}
		var votedUser map[string]int
		err = json.Unmarshal(r.VotedUser, &votedUser)
		if err != nil {
			return nil
		}
		result := Vote{
			Id:          r.Id,
			OrgId:       r.OrgId,
			Name:        r.Name,
			Img:         r.Img,
			Description: r.Description,
			BeginTime:   r.BeginTime,
			EndTime:     r.EndTime,
			Voters:      voters,
			VotedUser:   votedUser,
		}
		results = append(results, &result)
	}
	return results
}

func getVoteById(ID string, db *gorm.DB) *Vote {
	var res SavedVote
	db.Where("id = ?", ID).First(&res)
	var voters map[string]Voter
	err := json.Unmarshal(res.Voters, &voters)
	if err != nil {
		return nil
	}
	var votedUser map[string]int
	err = json.Unmarshal(res.VotedUser, &votedUser)
	if err != nil {
		return nil
	}
	result := Vote{
		Id:          res.Id,
		Name:        res.Name,
		OrgId:       res.OrgId,
		Img:         res.Img,
		Description: res.Description,
		BeginTime:   res.BeginTime,
		EndTime:     res.EndTime,
		Voters:      voters,
		VotedUser:   votedUser,
	}
	return &result
}

func createVote(vote Vote, db *gorm.DB) error {
	bytes, err := vote.toBytes()
	if err != nil {
		return err
	}
	return db.Create(bytes).Error
}

func updateVote(vote Vote, db *gorm.DB) error {
	t, err := vote.toBytes()
	if err != nil {
		return err
	}
	return db.Model(t).Updates(SavedVote{Voters: t.Voters, VotedUser: t.VotedUser}).Error
}
